package com.rs.adminweb.commons.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.jaxplat.JaxplatBean;
import com.jaxplat.delegate.CommonsJaxplatDelegate;
import com.jaxplat.exceptions.GeneralException;
import com.jaxplat.util.StringUtils;

public class FileUpload
{
    protected final Log logger = LogFactory.getLog(getClass());

    public void upload(HttpServletRequest request, HttpServletResponse response) throws GeneralException
    {
        String uploadRootPath = FileUploadUtils.getUplaodRootPath(request);

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(819200);

        factory.setRepository(new File(uploadRootPath));

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setHeaderEncoding("UTF-8");

        List items = null;
        try
        {
            items = upload.parseRequest(request);

            FileUploadEntity entity = parseFormField(items);

            File uploadPath = FileUploadUtils.parseUploadFilePath(uploadRootPath, entity);

            entity.setAbsolutePath(uploadPath.getAbsolutePath());

            List files = parseUploadFiles(items, entity, uploadPath);

            List fileIds = writeDatabase(files);

            writeClient(request, response, files);
        }
        catch (Exception e)
        {
            throw new GeneralException("\u6587\u4EF6\u4E0A\u4F20\u51FA\u73B0\u5F02\u5E38 \uFF01", e);
        }
    }

    public void writeClient(HttpServletRequest request, HttpServletResponse response, List files) throws ServletException, IOException
    {
        String fileId = "";
        String fileName = "";
        if (null != files && files.size() > 0)
        {
            FileUploadEntity entity = (FileUploadEntity) files.get(0);
            fileId = entity.getUploadId().toString();
            fileName = entity.getName();
        }
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("{result:true,msg:'sucesses',uploadId:'" + fileId + "',fileName:'" + fileName + "'}");
        out.flush();
        out.close();
    }

    private FileUploadEntity parseFormField(List items) throws Exception
    {
        FileUploadEntity entity = new FileUploadEntity();
        BeanWrapper bw = new BeanWrapperImpl(entity);

        Iterator iter = items.iterator();
        while (iter.hasNext())
        {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField())
            {
                String fieldName = item.getFieldName();
                String fieldValue = item.getString("UTF-8");
                if (bw.isWritableProperty(fieldName))
                {
                    bw.setPropertyValue(fieldName, fieldValue);
                }
                if (this.logger.isDebugEnabled())
                {
                    this.logger.debug(fieldName + "==" + fieldValue);
                }
            }

        }

        return entity;
    }

    private List parseUploadFiles(List items, FileUploadEntity entity, File uploadPath) throws Exception
    {
        List fileList = new ArrayList();
        Iterator iter = items.iterator();
        while (iter.hasNext())
        {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
            {
                continue;
            }
            String fileName = item.getName();
            String fileExt = "";

            int index = fileName.lastIndexOf(".");
            if (index != -1)
            {
                fileExt = fileName.substring(index + 1);
            }

            if (fileName.equals(""))
                continue;
            FileUploadEntity fun = (FileUploadEntity) entity.clone();

            String uploadFileName = parseFileName(uploadPath, fileName);

            fun.setName(uploadFileName);

            fun.setFileSize(new Long(item.getSize()));

            fun.setFileType(fileExt);

            fun.setDescription(fileName.substring(0, index));

            fun.setUploadTime(new Date(System.currentTimeMillis()));

            fileList.add(fun);

            File uploadFile = new File(uploadPath, uploadFileName);
            item.write(uploadFile);
        }

        return fileList;
    }

    public List writeDatabase(List files) throws GeneralException
    {
        CommonsJaxplatDelegate jaxDelegate = (CommonsJaxplatDelegate) JaxplatBean.getBean("commonsJaxplatDelegate");
        List fileIds = new ArrayList();
        Iterator iter = files.iterator();
        while (iter.hasNext())
        {
            FileUploadEntity entity = (FileUploadEntity) iter.next();
            jaxDelegate.save(entity);
            fileIds.add(entity.getUploadId());
        }

        if (this.logger.isDebugEnabled())
        {
            this.logger.debug("db ids == " + fileIds);
        }
        return fileIds;
    }

    public String parseFileName(File uploadPath, String fileName)
    {
        int index = fileName.lastIndexOf(".");
        String fileExt = fileName.substring(index);
        String name = fileName.substring(0, index);

        // File file = new File(uploadPath, fileName);
        UUID uuid = UUID.randomUUID();
        fileName = uuid.toString() + fileExt;

        // file = new File(uploadPath, fileName);

        return fileName;
    }

    public static void main(String[] args)
    {
        UUID uuid = UUID.randomUUID();
        System.out.println(uuid.toString());
    }
}